/**
 * 对公众平台发送给公众账号的消息加解密示例代码.
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

// ------------------------------------------------------------------------

package com.dycong.common.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * SHA1 class
 * <p/>
 * 计算公众平台的消息签名接口.
 */
public class SHA1 {

    /**
     * 用SHA1算法生成安全签名
     *
     * @param array 字符串
     * @return 安全签名
     */
    public static String getSHA1(String... array) throws NoSuchAlgorithmException {
        StringBuffer sb = new StringBuffer();
        // 字符串排序
        Arrays.sort(array);
        for (String item : array) {
            sb.append(item);
        }
        return getSHA1(sb.toString());
    }

    public static String getSHA1(String string) throws NoSuchAlgorithmException {
        // SHA1签名生成
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(string.getBytes());
        byte[] digest = md.digest();

        StringBuilder hexstr = new StringBuilder();
        String shaHex = "";
        for (byte aDigest : digest) {
            shaHex = Integer.toHexString(aDigest & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return hexstr.toString();
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String rawData = "{\"nickName\":\"Band\",\"gender\":1,\"language\":\"zh_CN\",\"city\":\"Guangzhou\",\"province\":\"Guangdong\",\"country\":\"CN\",\"avatarUrl\":\"http://wx.qlogo.cn/mmopen/vi_32/1vZvI39NWFQ9XM4LtQpFrQJ1xlgZxx3w7bQxKARol6503Iuswjjn6nIGBiaycAjAtpujxyzYsrztuuICqIM5ibXQ/0\"}";
        String key = "HyVFkGl5F5OQWJZZaNzBBg==";
        System.out.println("75e81ceda165f4ffa64f4068af58c64b8f54b88c".equals(getSHA1(rawData + key)));
    }
}
